<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use think\Config;
use think\Hook;
use think\Session;
use think\Validate;



/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');
    }

    /**
     * 后台首页
     */
    public function index()
    {
        $cookieArr = ['adminskin' => "/^skin\-([a-z\-]+)\$/i", 'multiplenav' => "/^(0|1)\$/", 'multipletab' => "/^(0|1)\$/", 'show_submenu' => "/^(0|1)\$/"];
        foreach ($cookieArr as $key => $regex) {
            $cookieValue = $this->request->cookie($key);
            if (!is_null($cookieValue) && preg_match($regex, $cookieValue)) {
                config('fastadmin.' . $key, $cookieValue);
            }
        }
        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'general'   => ['new', 'purple'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->assignconfig('cookie', ['prefix' => config('cookie.prefix')]);
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

	//created by guruijun 2022-11-19	
	public function getUserByCAS()   
    {  
		//dump($_SERVER);
        header("Content-Type: text/html; charset=utf-8");
		//open session
		//session_start(); 
		//引入文件
		require_once dirname(__FILE__)."/CAS/CAS.php";  
		//指定log文件
		\phpCAS::setDebug('./log.log');

		//指定cas地址，最后一个true表示是否cas服务器为https，第二个参数为域名或是ip，第三个参数为服务器端口号，第四个参数为上下文路径
		\phpCAS::client(CAS_VERSION_2_0,'authserver.jit.edu.cn',443,'authserver',false);

		//设置no ssl，即忽略证书检查.如果需要ssl，请用 phpCAS::setCasServerCACert()设置
		//setCasServerCACert方法设置ssl证书，
		\phpCAS::setNoCasServerValidation();
		\phpCAS::handleLogoutRequests();
		\phpCAS::forceAuthentication();

		//本地退出应该重定向到CAS进行退出，传递service参数可以使CAS退出后返回本应用
		//demo表示退出请求为logout的请求
		/*if(isset($_GET['logout'])){
			$param = array('service'=>'http://ssodemo.test.com/cas/index.php');
			phpCAS::logout($param);
			exit;
		}*/

		return \phpCAS::getUser();
		///phpCAS::getAttributes() 可以返回所有所有授权的属性
		/*echo "<pre>";
		echo "user:".\phpCAS::getUser();
		echo "<br/>";
		echo "*******************";
		echo "<br/>";
		echo "attributes:";
		echo "<br/>";
		//var_dump(\phpCAS::getAttributes());
		*/
    } 
	
	//php获取当前访问的完整url地址
	public function GetCurUrl()
	{
		$url='http://';
		if(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on'){
		$url='https://';
		}

		if($_SERVER['SERVER_PORT']!='80'){
		$url.=$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
		}else{

		$url.=$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
		}
		return $url;
	}
	
    /**
     * 管理员登录
     */
    public function login()
	 
    {
		
		 $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }
		
		$cas='';
		if(isset($_GET['cas']))
		{
			$cas=$_GET['cas'];
		}
		
		if($cas=='')//统一身份认证进入
		{
			//获取UID
		$username=$this->getUserByCAS();
		
	   if(strlen($username)==11)//统一身份认证
	   {
	        $username = $username;
            $password = 'Jit@985';//固定密码
            $keeplogin =0;
           // $token = $this->request->post('__token__');//？？？？/
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
               // '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
               // '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                //$rule['captcha'] = 'require|captcha';
               // $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }
		}
		else if ($this->request->isPost())  //普通登录
		 
	   
		{
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            Session::delete("referer");
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = $background ? (stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background) : '';
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $this->auth->logout();
            Hook::listen("admin_logout_after", $this->request);
           // $this->success(__('Logout successful'), 'index/login');
		   $this->success(__('Logout successful'), 'http://ehall.jit.edu.cn/new/index.html');
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }

}
